package com.whfc.hj.codec;

import com.whfc.hj.entity.HjConst;
import com.whfc.hj.entity.HjMsg;
import com.whfc.hj.entity.HjMsg2011WC;
import com.whfc.hj.util.HjMsgUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class HjMsgDecoder extends MessageToMessageDecoder<ByteBuf> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final int MIN_LEGNTH = 100;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
        if (!in.isReadable()) {
            return;
        }
        logger.debug(ByteBufUtil.prettyHexDump(in));
        int totalLength = in.readableBytes();
        String msgStr = in.readCharSequence(totalLength, HjConst.UTF8).toString();
        logger.info("接收数据:{}", msgStr);
        if (totalLength > MIN_LEGNTH) {
            HjMsg2011WC msg = HjMsgUtil.decodeWC(msgStr);
            out.add(msg);
        }

    }

}
